/* 
 * Copyright 2014 ShangDao.Ltd  All rights reserved.
 * SiChuan ShangDao.Ltd PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * @BaBaseApplication.java  2014-9-9 上午10:19:15 - Carson
 * @author YanXu
 * @email:981385016@qq.com
 * @version 1.0
 */

package com.android.tiango.baba;

import android.app.Application;

import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.entity.BaseDataEntity;

public class BaBaseApplication extends Application {
	private static BaBaseApplication mInstance;
	public static int mWidth;
	public static int mHeight;
	public static long mServerTime = 11;
	private static int countTree = 0;// 获取时间次数
	public static long ccTimeTree;// 服务器与本地时间差

	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = this;
		mWidth = getResources().getDisplayMetrics().widthPixels;
		mHeight = getResources().getDisplayMetrics().heightPixels;
		getmServerTime();
	}

	public static BaBaseApplication getAppContext() {
		return mInstance;
	}

	private static void getServerTime() {
		final long crt = System.currentTimeMillis();
		HttpClientAsync clientAsync = HttpClientAsync.getInstance();
		clientAsync.get(HttpUrl.getUrl(HttpUrl.GETSERVERTIME), new HttpCallBack() {

			@Override
			public void onHttpSuccess(Object arg0) {
				long c = System.currentTimeMillis() - crt;
				BaseDataEntity entity = (BaseDataEntity) arg0;
				long mcServerTime = Long.valueOf(entity.getData());
				ccTimeTree = (mcServerTime + c / 2) - System.currentTimeMillis();
				BaBaseApplication.setmServerTime(mServerTime);
				if (c > 2000) {
					if (countTree < 5) {
						countTree++;
						getServerTime();
					} else {
						mServerTime = 12;
						ccTimeTree = ShareCookie.getCCTime();
						return;
					}
				} else {
					mServerTime = 12;
					ShareCookie.saveCCTime(ccTimeTree);
				}
			}

			@Override
			public void onHttpStarted() {

			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				mServerTime = 11;
			}
		}, BaseDataEntity.class);
	}

	public static long getmServerTime() {
		if (mServerTime == 11) {
			getServerTime();
		} else {
			mServerTime = System.currentTimeMillis() + ccTimeTree;
		}
		return System.currentTimeMillis() + ccTimeTree;

	}

	public static void setmServerTime(long mServerTime) {
		BaBaseApplication.mServerTime = mServerTime;
	}

}